﻿using System;
using System.Runtime.InteropServices;

namespace Eflong.Structure
{
    /// <summary>
    ///系统时间类
    /// </summary>
    [StructLayout( LayoutKind.Sequential )]
    public struct SystemTime
    {
        public ushort year;
        public ushort month;
        public ushort dayofweek;
        public ushort day;
        public ushort hour;
        public ushort minute;
        public ushort second;
        public ushort milliseconds;

        public static SystemTime GetAsSystemTime( DateTime time )
        {
            return new SystemTime
                       {
                           year = ( ushort )time.Year ,
                           month = ( ushort )time.Month ,
                           dayofweek = ( ushort )time.DayOfWeek ,
                           day = ( ushort )time.Day ,
                           hour = ( ushort )time.Hour ,
                           minute = ( ushort )time.Minute ,
                           second = ( ushort )time.Second ,
                           milliseconds = ( ushort )time.Millisecond
                       };
        }

        public static DateTime GetDateTimeFromSystemTime( SystemTime systemTime )
        {
            return Validate( systemTime ) ? new DateTime( systemTime.year , systemTime.month , systemTime.day , systemTime.hour , systemTime.minute , systemTime.second ) : DateTime.Now;
        }

        public static bool Validate( SystemTime systemTime )
        {
            return ( systemTime.year >= 2000 && systemTime.month <= 12 && systemTime.day <= 31 ) && systemTime.hour <= 24 && systemTime.minute <= 59 && systemTime.second <= 59;
        }

        [DllImport( "Kernel32.dll" )]
        private static extern bool SetSystemTime( [In , Out] SystemTime st );

        public static bool SetSysTime( SystemTime st )
        {
            return SetSystemTime( st );
        }
    }
}